package com.cn.modules.user.model;

import java.util.Date;
import java.util.List;

import com.cn.common.utils.GeneratorKey;
import com.cn.common.utils.Message;
import com.cn.common.utils.StringUtil;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

/**
 * `id` varchar(32) NOT NULL, `name` varchar(32) NOT NULL, `loginName`
 * varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `usableFlag` char(1)
 * DEFAULT NULL, `lastDate` datetime DEFAULT NULL,
 * 
 * @author Administrator
 *
 */
public class User extends Model<User> {
	private static final long serialVersionUID = 1L;
	public static final User me = new User();

	public static final String  SUCCESS="保存成功!";
	public static final String  FAILURE="保存失败!";
	/**
	 * 所有 sql 与业务逻辑写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
	 */
	/**
	 * 分页查询
	 * @param pageNumber
	 * @param pageSize
	 * @param sidx
	 * @param sord
	 * @return
	 */
	public Page<User> selectJqGridPage(int pageNumber, int pageSize,String sidx, String sord) {
		sidx = StringUtil.isNull(sidx) ? " lastDate" : sidx;
		sord = StringUtil.isNull(sord) ? " asc" : sord;
		
		return paginate(pageNumber, pageSize, "select *", "from user order by "+ sidx +"  "+ sord);
	}
	
	
	public static Message saveUser(User user) {
		boolean result=false;
		try {
			if(StringUtil.isNull(user.getStr("id"))){
				user.set("id", GeneratorKey.genaraId());
				user.set("lastDate", new Date());
				result= user.save();
			 }else{
				 result= user.update();
			 }
			 if(result)
				 return new Message(result, SUCCESS);
			 else
				 return new Message(result, FAILURE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 return new Message(result, SUCCESS);
	}
	
	/**
	 * 验证主键是否存在
	 * @param key
	 * @return
	 */
	public static boolean checkKey(String key){
		User tmp=User.me.findById(key);
		return tmp!=null ?false:true;
	}
	
	public User login(String userName,String passWord){
		List<User> list=User.me.find("select * from USER where loginName=? AND passWord=?", userName,passWord);
		if(list==null ||list.size()==0)
			return null;
		else
			return list.get(0);
	}
	
}
